package com.yu.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.crm.config.StatusCode;
import com.yu.crm.domain.pojo.CrmMenu;
import com.yu.crm.domain.pojo.CrmRoleMenuLink;
import com.yu.crm.mapper.CrmMenuMapper;
import com.yu.crm.service.CrmMenuService;
import com.yu.crm.service.CrmRoleMenuLinkService;
import com.yxzz.common.config.UserCacheManager;
import com.yxzz.common.exception.GeneralException;
import com.yxzz.common.helper.DataHelpers;
import com.yxzz.common.helper.DateHelpers;
import com.yxzz.common.helper.ExceptionHelpers;
import com.yxzz.common.helper.valid.ValidatorHelpers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author donnie-bin
 * @since 2019-06-10
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CrmMenuServiceImpl extends ServiceImpl<CrmMenuMapper, CrmMenu> implements CrmMenuService {
    @Autowired
    UserCacheManager userCacheManager;
    @Autowired
    CrmRoleMenuLinkService crmRoleMenuLinkService;

    @Override
    public boolean saveOrUpdate(CrmMenu entity) {
        if(DataHelpers.isEmpty(entity.getId())){
            QueryWrapper<CrmMenu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("pid",entity.getPid());
            queryWrapper.eq("is_deleted",0);
            int count = super.count(queryWrapper);
            if(DataHelpers.isNotInteger(count)){
                entity.setViewOrder(count+1);
            }

            LambdaQueryWrapper<CrmMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(CrmMenu::getPid, entity.getPid());
            lambdaQueryWrapper.eq(CrmMenu::getMenuName, entity.getMenuName());
            int oldCount = super.count(lambdaQueryWrapper);
            ValidatorHelpers.validateDataExist("子菜单名称不能重复", oldCount);
            entity.setGmtCreate(DateHelpers.now());
            entity.setGmtModified(DateHelpers.now());
            return ExceptionHelpers.checkData(super.save(entity), "新增失败");
        }else{
            entity.setGmtModified(DateHelpers.now());
            return ExceptionHelpers.checkData(super.updateById(entity), "修改失败");
        }
    }

    @Override
    public boolean removeById(Serializable id) {
        boolean flag = ExceptionHelpers.checkData(super.removeById(id), "删除失败");
        if(flag){
            QueryWrapper<CrmRoleMenuLink> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("menu_id",id);
            queryWrapper.eq("is_deleted",0);

            crmRoleMenuLinkService.remove(queryWrapper);
        }
        return flag;
    }

    @Override
    public List<CrmMenu> treeList(Integer pid) {
        return baseMapper.selectTreeList(pid);
    }

    @Override
    public List<CrmMenu> treeList1(Integer pid) {
        List<CrmMenu> list=new ArrayList<>();
        List<CrmMenu> crmMenuList = baseMapper.selectTreeList(pid);
        if(pid!=null && pid==0){
            CrmMenu crmMenu=new CrmMenu();
            crmMenu.setId(0);
            crmMenu.setMenuDescription("根目录");
            crmMenu.setMenuName("根目录");
            crmMenu.setPid(0L);
            crmMenu.setViewOrder(1);
            if(DataHelpers.isNotEmpty(crmMenuList)){
                crmMenu.setChildren(crmMenuList);
            }
            list.add(crmMenu);
            return list;
        }else{
            return crmMenuList;
        }
    }

    /**
     * 通过地址url查询地址详情
     * @param pageRouter
     * @return
     */
    @Override
    public CrmMenu getByPageRouter(String pageRouter) {
        CrmMenu crmMenu =null;
        String[] split = pageRouter.substring(1).split("/");
        QueryWrapper<CrmMenu> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("page_router",split[0]);
        crmMenu = baseMapper.selectOne(queryWrapper);
        if(split.length>1){
            QueryWrapper<CrmMenu> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("page_router",split[1]);
            crmMenu = baseMapper.selectOne(queryWrapper1);
        }
        return crmMenu;
    }

    /**
     * 通过部门编号向上移动一位排序
     * @param id 部门编号
     */
    @Override
    public void updateSort(Integer id) {
        List<CrmMenu> crmMenuList=new ArrayList<>();
        CrmMenu newCrmMenu= baseMapper.selectById(id);
        if(DataHelpers.isNotEmpty(newCrmMenu)){
            QueryWrapper<CrmMenu> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("pid",newCrmMenu.getPid());
            queryWrapper.eq("is_deleted",0);
            queryWrapper.orderByAsc("view_order");
            List<CrmMenu> list= baseMapper.selectList(queryWrapper);
            if(DataHelpers.isNotEmpty(list)){
                int i=0;
                for(CrmMenu crmMenu:list){
                    if(!crmMenu.getId().equals(newCrmMenu.getId())){
                        i++;
                    }else{
                        break;
                    }
                }

                if(i>=1){
                    CrmMenu oldCrmMenu = list.get(i - 1);
                    if(DataHelpers.isNotEmpty(oldCrmMenu)){
                        //新排序
                        Integer sort = oldCrmMenu.getViewOrder();
                        oldCrmMenu.setViewOrder(newCrmMenu.getViewOrder());
                        newCrmMenu.setViewOrder(sort);

                        crmMenuList.add(newCrmMenu);
                        crmMenuList.add(oldCrmMenu);
                    }
                }
                if(DataHelpers.isNotEmpty(crmMenuList)){
                    saveOrUpdateBatch(crmMenuList);
                }
            }
        }else{
            throw new GeneralException("此菜单编号无效");
        }
    }

    /**
     * 根据当前用户获取菜单列表
     * @return
     */
    @Override
    public List<HashMap<String,Object>> getMenusByUserId(String userId) {
        if(!DataHelpers.isNotEmpty(userId)){
            userId = userCacheManager.getCurrentUser().getUserId();
        }
        Integer roleType = baseMapper.isRoleType(userId, StatusCode.ROLETYPE3);
        if(DataHelpers.isNotInteger(roleType)){
            //查询所有菜单权限
            return baseMapper.getMenus();
        }else{
            return baseMapper.getMenusByUserId(userId);
        }
       /* if(DataHelpers.isNotEmpty(list)){
            //集合转数形结合
            return TreeUtils.listToTree(list, "id", "pid", "children");
        }
        return list;*/
    }
}
